package tcp1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoSever {
    private ServerSocket serverSocket = null;

    public TcpEchoSever(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");

        while (true){
            //通过accept 方法“接听电话”，然后才能进行通信
            Socket clientSocket  = serverSocket.accept();

            Thread thread = new Thread(()->{  //利用多线程来解决多个客户端同时请求
                processConnection(clientSocket);
            });
            thread.start();
        }
    }

    //通过这个方法来处理一次连接，连接建立的过程中就会涉及到多次的请求响应交互
    private void processConnection(Socket clientSocket) {
        System.out.printf("[%s,%d] 客户端上线！",clientSocket.getInetAddress(),clientSocket.getPort());
        //循环的读取客户端的请求并返回响应

        try(InputStream inputStream = clientSocket.getInputStream();   //tcp面向字节流（和文件类似）
            OutputStream outputStream = clientSocket.getOutputStream()){
            while (true){
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()){
                    //读取完毕，客户端断开连接，就会产生读取完毕
                    System.out.printf("[%s,%d] 客户端下线！",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                //1.读取请求并解析，这里隐藏的约定，next读的时候要读到空白符才会结束
                //   因此就要求客户端发来的请求必须带有空白符的结尾
                String request = scanner.next();

                //2根据请求计算响应
                String response = process(request);

                //3，把响应返回给客户端
                //通过这种方式可以写回，但是这种方式不方便给返回的响应中添加 \n
                //outputStream.write(response.getBytes(),0,response.getBytes().length);
                //也可以给outputStream套上一层，完成更方便的写入
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                printWriter.flush();

                //打印日志
                System.out.printf("[%s:%d] req: %s,resp: %s\n",clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(),request,response) ;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                clientSocket.close();//释放文件本体
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoSever tcpEchoSever = new TcpEchoSever(9090);
        tcpEchoSever.start();
    }
}
